package com.ojoin.trade.common_core.web.service.impl;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.ojoin.trade.common.Constants;
import com.ojoin.trade.common.constdef.IConstDef;
import com.ojoin.trade.common.exception.BusinessException;
import com.ojoin.trade.common.exception.IPayResponseCodeConst;
import com.ojoin.trade.common.utils.CommonUtils;
import com.ojoin.trade.common.utils.LogUtils;
import com.ojoin.trade.common.utils.UUIDUtils;
import com.ojoin.trade.common.utils.json.JSONUtils;
import com.ojoin.trade.common.utils.paynow.HttpPost;
import com.ojoin.trade.common.utils.paynow.IAccountConst;
import com.ojoin.trade.common.utils.paynow.Packages;
import com.ojoin.trade.common.utils.paynow.Unpack;
import com.ojoin.trade.common.web.dao.BaseDao;
import com.ojoin.trade.common.web.service.impl.BaseServiceImpl;
import com.ojoin.trade.common_core.web.dao.TbMerchantUserDao;
import com.ojoin.trade.common_core.web.domain.TbMerchantUser;
import com.ojoin.trade.common_core.web.domain.TbMerchantUserBusinessType;
import com.ojoin.trade.common_core.web.service.MerchantUserBaseService;

@Service
public class MerchantUserBaseServiceImpl extends
		BaseServiceImpl<TbMerchantUser> implements MerchantUserBaseService {
	@Autowired
	private TbMerchantUserDao dao;
	private Logger log = LoggerFactory
			.getLogger(MerchantUserBaseServiceImpl.class);

	@Override
	protected BaseDao<TbMerchantUser> getBaseDao() {
		return dao;
	}

	@Override
	public List login(String username, String password) {
		String mchNo = null; // 没有账户的商户id
		Packages packages = new Packages();
		Unpack unpack = new Unpack();
		Map<String, String> map = new HashMap<String, String>();
		List list = null;
		String requestReport = "";
		String funcode = IAccountConst.LOGIN_FUC;
		map.put("loginNo", username);
		map.put("passwd", password);
		requestReport = packages.returnMess(funcode, map);
		requestReport = "requestReport=" + requestReport;
		String xml = HttpPost.http(IAccountConst.MHT_IP, requestReport);
		log.info("登陆名{}尝试登陆系统",new String[]{username});
		list = unpack.unpack(xml, Constants.ENCODING);
            
		return list;
	}

	@Override
	public int registerJoinUser(String mthNo,String userAccount) throws BusinessException {

		TbMerchantUser user = ((TbMerchantUserDao) getBaseDao())
				.queryUserByPaynow(mthNo);
		if (user == null) {
			TbMerchantUser joinuservo = new TbMerchantUser();
			joinuservo.setUserIdOfIPayNow(mthNo);
			joinuservo.setUserAccount(userAccount);
			getBaseDao().insert(joinuservo);
			return joinuservo.getId();
		} else {
			return user.getId();
		}

	}

	@Override
	public String queryPayUserByJoinUserID(int joinuserNo)
			throws BusinessException {
		TbMerchantUser uservo = getBaseDao().selectById(joinuserNo);
		if (uservo == null)
			return null;
		else {
			return uservo.getUserIdOfIPayNow();
		}
	}

	@Override
	public List queryPayUserVOByID(String mthNo) throws BusinessException {
		Packages packages = new Packages();
		Unpack unpack = new Unpack();
		Map<String, String> map = new HashMap<String, String>();
		List list = null;
		String requestReport = "";
		String funcode = IAccountConst.QUERYMER_FUC;
		map.put("funcode", funcode);
		map.put("mhtNo", mthNo);
		requestReport = packages.returnMess(funcode, map);
		requestReport = "requestReport=" + requestReport;
		String xml = HttpPost.http(IAccountConst.MHT_IP, requestReport);
		log.info("商户号{}尝试查询商户信息",new String[]{mthNo});
		list = unpack.unpack(xml, Constants.ENCODING);

		return list;
	}

	@Override
	public List preRealNameByPayUser(String mchNo) throws BusinessException {
		List list = null;
		try {
			Packages packages = new Packages();
			Unpack unpack = new Unpack();
			Map<String, String> map = new HashMap<String, String>();
			String requestReport = "";
			String funcode = IAccountConst.PREAUTICATION_FUC;
			map.put("mhtNo", mchNo);
			requestReport = packages.returnMess(funcode, map);
			requestReport = "requestReport=" + requestReport;
			String xml = HttpPost.http(IAccountConst.MHT_IP, requestReport);
			log.info("商户号{}获取Token", new String[] { mchNo });
			list = unpack.unpack(xml, Constants.ENCODING);
		} catch (Exception e) {
			throw new BusinessException(e.getMessage());
		}
		return list;

	}

	@Override
	public List realNameEnterpriseByPayUserInfo(String mchNo,
			String mchName, String mobile, String name, String certNo,
			String licNo, String taxNo, String certDate, String openNo,
			String orgNo, String cardMobile, String cardNo,
			String cardProvince, String cardCity, String branchNo)
			throws BusinessException {
		Packages packages = new Packages();
		Unpack unpack = new Unpack();
		Map<String, String> map = new HashMap<String, String>();
		List list = null;
		String requestReport = "";
		String funcode = IAccountConst.AUTICATION_FUC;
		map.put("mhtNo", mchNo);
		map.put("mchType", IAccountConst.AUTICATION_MCHTYPE_ENTERPRISE);
		map.put("mchName", mchName);
		map.put("mobile", mobile);
		map.put("name", name);
		map.put("certNo", certNo);
		map.put("certDate", certDate);
		map.put("licNo", licNo);
		map.put("taxNo", taxNo);
		map.put("openNo", openNo);
		map.put("orgNo", orgNo);
		map.put("cardMobile", cardMobile);
		map.put("cardNo", cardNo);
		map.put("cardProvince", cardProvince);
		map.put("cardCity", cardCity);
		map.put("branchNo", branchNo);
		String orderid = UUIDUtils.create();
		map.put("orderId", orderid);
		requestReport = packages.returnMess(funcode, map);
		requestReport = "requestReport=" + requestReport;
		String xml = HttpPost.http(IAccountConst.MHT_IP, requestReport);
		LogUtils.info(log,JSONUtils.toJSONString(map));
		LogUtils.info(log, "商户号{}，订单号{}，商户类型{}，商户名称{}尝试企业实名认证",mchNo,orderid,IAccountConst.AUTICATION_MCHTYPE_ENTERPRISE,mchName);
		list = unpack.unpack(xml, Constants.ENCODING);
            
		return list;
	}
	
	
	@Override
	public List realNameIndividualByPayUserInfo(String mchNo,String mchName, String mobile,
			String name, String certNo, String certDate,
			String cardMobile, String cardNo,
			String cardProvince, String cardCity, String branchNo)
			throws BusinessException {
		Packages packages = new Packages();
		Unpack unpack = new Unpack();
		Map<String, String> map = new HashMap<String, String>();
		List list = null;
		String requestReport = "";
		String funcode = IAccountConst.AUTICATION_FUC;
		map.put("mhtNo", mchNo);
		map.put("mchType", IAccountConst.AUTICATION_MCHTYPE_INDIVIDUAL);
		map.put("mchName", mchName);
		map.put("mobile", mobile);
		map.put("name", name);
		map.put("certNo", certNo);
		map.put("certDate", certDate);
		map.put("cardMobile", cardMobile);
		map.put("cardNo", cardNo);
		map.put("cardProvince", cardProvince);
		map.put("cardCity", cardCity);
		map.put("branchNo", branchNo);
		String orderid = UUIDUtils.create();
		map.put("orderId", orderid);
		requestReport = packages.returnMess(funcode, map);
		requestReport = "requestReport=" + requestReport;
		String xml = HttpPost.http(IAccountConst.MHT_IP, requestReport);
		log.info("商户号{},订单号{},商户类型{},姓名{}尝试个人实名认证",new String[]{mchNo,orderid, IAccountConst.AUTICATION_MCHTYPE_INDIVIDUAL,name});
		list = unpack.unpack(xml, Constants.ENCODING);
	
		return list;
	}

	@Override
	public List updateLoginPwd(String mchNo, String oldPasswd, String newPasswd)
			throws BusinessException {
		Packages packages = new Packages();
		Unpack unpack = new Unpack();
		Map<String, String> map = new HashMap<String, String>();
		List list = null;
		String requestReport = "";
		String funcode = IAccountConst.ALTERPWD_FUC;
		map.put("funcode", funcode);
		map.put("mhtNo", mchNo);
		map.put("pwdType", "01");
		map.put("oldPasswd", oldPasswd);// 原密码
		map.put("newPasswd", newPasswd);// 新密码
		String orderid = UUIDUtils.create();
		map.put("orderId", orderid);// 业务操作日志id
		requestReport = packages.returnMess(funcode, map);
		requestReport = "requestReport=" + requestReport;
		String xml = HttpPost.http(IAccountConst.MHT_IP, requestReport);
		log.info("商户号{},订单号{}尝试更改登陆密码",new String[]{mchNo,orderid});
		list = unpack.unpack(xml, Constants.ENCODING);

        return list;
	}

	@Override
	public List updatePayPwd(String mchNo, String oldPasswd, String newPasswd)
			throws BusinessException {
		Packages packages = new Packages();
		Unpack unpack = new Unpack();
		Map<String, String> map = new HashMap<String, String>();
		List list = null;
		String requestReport = "";
		String funcode = IAccountConst.ALTERPWD_FUC;
		map.put("funcode", funcode);
		map.put("mhtNo", mchNo);
		map.put("pwdType", "02");
		map.put("oldPasswd", oldPasswd);// 原密码
		map.put("newPasswd", newPasswd);// 新密码
		String orderid = UUIDUtils.create();
		map.put("orderId", orderid);// 业务操作日志id
		requestReport = packages.returnMess(funcode, map);
		requestReport = "requestReport=" + requestReport;
		String xml = HttpPost.http(IAccountConst.MHT_IP, requestReport);
		log.info("商户号{},订单号{}尝试更改支付密码",new String[]{mchNo,orderid});
		list = unpack.unpack(xml, Constants.ENCODING);

        return list;
	}

	@Override
	public List setPayPwd(String mchNo, String newPasswd)
			throws BusinessException {
		Packages packages = new Packages();
		Unpack unpack = new Unpack();
		Map<String, String> map = new HashMap<String, String>();
		List list = null;

		String requestReport = "";
		String funcode = IAccountConst.SERPWD_FUC;
		map.put("funcode", funcode);
		map.put("mhtNo", mchNo);
		map.put("pwdType", "02");
		map.put("newPasswd", newPasswd);// 新密码
		String orderId = UUIDUtils.create();
		map.put("orderId", orderId);// 业务操作日志id
		requestReport = packages.returnMess(funcode, map);
		requestReport = "requestReport=" + requestReport;
		String xml = HttpPost.http(IAccountConst.MHT_IP, requestReport);
		// String xml = HttpsExample.httpsExample( + requestReport) ;
		log.info("商户号{},订单号{},尝试设置支付密码",new String[]{mchNo,orderId});
		list = unpack.unpack(xml, Constants.ENCODING);
		return list;
	}

	@Override
	public TbMerchantUser queryJoinUserInfoById(int joinuserNo)
			throws BusinessException {
		return getBaseDao().selectById(joinuserNo);
	}

	@Override
	public TbMerchantUser queryJoinUser(String mthNo) throws BusinessException {
		TbMerchantUser user = ((TbMerchantUserDao) getBaseDao())
				.queryUserByPaynow(mthNo);
		return user;
	}

	@Override
	public String queryJoinUserByLoginNo(String loginNo) throws BusinessException {
		return ((TbMerchantUserDao) getBaseDao()).queryNameByLoginNo(loginNo);
	}
	
	
	@Override
	public int updateUserBalanceAfterTransfer(int joinuserNo, long radio,
			long fee, long balance, String operatetype) throws BusinessException {
		TbMerchantUser user = null;
		try {
			user = getBaseDao().selectById(joinuserNo);
			String userfee = user.getT0FeeBalance();
			String userbalance = user.getT0LoanBalance();
			String userradio = user.getT0RatioFeeBalance();
            if(StringUtils.isEmpty(userfee)){
                userfee="0";
            }
            if(StringUtils.isEmpty(userbalance)){
                userbalance="0";
            }
            if(StringUtils.isEmpty(userradio)){
                userradio="0";
            }
			if (IConstDef.T0_LOAN_CREDIT.equalsIgnoreCase(operatetype) ||
				IConstDef.T1_LOAN_CREDIT.equalsIgnoreCase(operatetype) ||
				IConstDef.D1_LOAN_CREDIT.equalsIgnoreCase(operatetype) ) {

				Long userbalong = new Long(userbalance);
				Long balacelong = new Long(balance);
				long newbanlace = userbalong + balacelong;
				user.setT0LoanBalance(new Long(newbanlace).toString());
				
				Long userradiolong = new Long(userradio);
				Long radiolong = new Long(radio);
				long newradio = userradiolong + radiolong;
				user.setT0RatioFeeBalance(new Long(newradio).toString());
				
				Long userfeelong = new Long(userfee);
				Long feelong = new Long(fee);
				long newfee = userfeelong + feelong;
				user.setT0FeeBalance(new Long(newfee).toString());
			}
			if (IConstDef.T0_LOAN_RETURN.equalsIgnoreCase(operatetype) ||
					IConstDef.T1_LOAN_RETURN.equalsIgnoreCase(operatetype) ||
					IConstDef.D1_LOAN_RETURN.equalsIgnoreCase(operatetype) ) {
				Long userbalong = new Long(userbalance);
				Long balacelong = new Long(balance);
				long newbanlace = userbalong - balacelong;
				user.setT0LoanBalance(new Long(newbanlace).toString());
				
//				还款只更新负债额，不更新手续费和利息
//				Long userradiolong = new Long(userradio);
//				Long radiolong = new Long(radio);
//				long newradio = userradiolong - radiolong;
//				user.setT0RatioFeeBalance(new Long(newradio).toString());
//				
//				Long userfeelong = new Long(userfee);
//				Long feelong = new Long(fee);
//				long newfee = userfeelong - feelong;
//				user.setT0FeeBalance(new Long(newfee).toString());
			}
			return getBaseDao().updateById(user);

		} catch (Exception e) {
			throw new BusinessException(e.getMessage());
		}

	}

	@Override
	public String selectTsByID(int id, String tablename)
			throws BusinessException {
		return ((TbMerchantUserDao) getBaseDao())
				.selectTsByID(id, tablename);
	}

    @Override
    public TbMerchantUser queryUserByCompany(int id) throws BusinessException {
        return  ((TbMerchantUserDao) getBaseDao()).queryUserByCompany(id);
    }

	@Override
	public TbMerchantUserBusinessType queryBusinessTypeByJoinuserId(int joinuserid)
			throws BusinessException {
		return ((TbMerchantUserDao) getBaseDao()).queryBusinessTypeByJoinuserId(joinuserid);
	}
    
	@Override
    public int updateShortnameById(int joinuserid, String shortname) throws BusinessException {
        return  ((TbMerchantUserDao) getBaseDao()).updateShortnameById(joinuserid, shortname);
    }
	
	@Override
	public boolean isExistsDebtByMhtno(Map param)
			throws BusinessException {
		String mhtNo = (String) param.get("mhtNo");
		//TODO:临时测试代码
		if("mchId20151229000000000000000000000000013".equals(mhtNo)){
			return true;
		}

		TbMerchantUser uservo = ((TbMerchantUserDao) getBaseDao()).queryUserByPaynow(mhtNo);
		if (uservo == null)
			throw new BusinessException("mhtNo->" + mhtNo + "不是有效的九盈商户，请检查.",IPayResponseCodeConst.ERR_INVALIDMTHNO);
		
		TbMerchantUserBusinessType queryvo = ((TbMerchantUserDao) getBaseDao()).queryBusinessTypeByJoinuserId(uservo.getId());
		if (queryvo == null)
			throw new BusinessException("mhtNo->" + mhtNo + "未查询到有效的九盈负债信息，请检查.",IPayResponseCodeConst.ERR_INVALIDMTHNO);
		
		if (CommonUtils.getLong(queryvo.getSlLoanUnpaiedBalance()) > 0 || 
			CommonUtils.getLong(queryvo.getT0LoanUnpaiedBalance()) > 0 || 
			CommonUtils.getLong(queryvo.getT1LoanUnpaiedBalance()) > 0)
			return true;
		
		return false;
	}
}